package com.qf.springboot.config;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ShiroConfig {

    @Bean
    //ShiroFilterChainDefinition接口 Shiro过滤器链定义 实现类是下面的DefaultShiroFilterChainDefinition
    public ShiroFilterChainDefinition shiroFilterChainDefinition(){
        DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition();

        //definition.addPathDefinition 添加路径的定义 默认所有页面都需要登录 下面所有的第二个参数是 特殊规则的字符串
        // authc 登录后才可以访问
        definition.addPathDefinition("/a.html","authc");

        // 登录后才可以访问,需要用户权限
        definition.addPathDefinition("/b.html","authc,roles[admin]");

        // url需要当前用户拥有document:read权限才可以访问
        definition.addPathDefinition("/c.html","perms[document:read]");

        // anon url无需登录即可访问
        definition.addPathDefinition("/d.html","anon");
        definition.addPathDefinition("/regist.html","anon");
        definition.addPathDefinition("/user/login","anon");
        definition.addPathDefinition("/user/register","anon");

        definition.addPathDefinition("/error","anon");

        //如下配置代表, /home 资源可以使用 免登录(RememberMe) cookie直接访问 user 代表 过滤器名字
        definition.addPathDefinition("/home.html","user");

        //默认所有的url都要登录后才可以访问,但是上面配置了的anno 的url除外
        //definition.addPathDefinition("/**","authc");

        return definition;
    }

    @Bean
    // Realm 获取信息的
    public Realm realm(){
        CustomRealm customRealm = new CustomRealm();

        // 设置密码处理方式 hashed凭证匹配器
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();

        // 设置md5加密
        hashedCredentialsMatcher.setHashAlgorithmName("md5");

        // 设置散列次数
        hashedCredentialsMatcher.setHashIterations(1024);

        customRealm.setCredentialsMatcher(hashedCredentialsMatcher);

        return customRealm;
    }
}
